package com.onehouse.infrastructure.repository.payment;

import com.onehouse.domain.payment.adapter.repository.IPaymentRepository;
import com.onehouse.domain.payment.model.entity.OrderPaymentRequest;
import com.onehouse.domain.payment.model.entity.Payment;
import com.onehouse.domain.payment.model.valobj.PaymentMethod;
import com.onehouse.domain.payment.model.valobj.PaymentStatus;
import com.onehouse.infrastructure.dao.PaymentDao;
import com.onehouse.infrastructure.dao.po.PaymentPo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

@Repository
public class PaymentRepository implements IPaymentRepository {

    private final PaymentDao paymentDao;

    public PaymentRepository(PaymentDao paymentDao) {
        this.paymentDao = paymentDao;
    }

    @Override
    public void doSavePayment(Payment payment) {
        PaymentPo paymentPo = new PaymentPo();
        BeanUtils.copyProperties(payment, paymentPo);
        paymentPo.setPaymentMethod(payment.getPaymentMethod().name());
        paymentPo.setStatus(payment.getStatus().name());
        
        PaymentPo existingPayment = paymentDao.selectByPaymentId(payment.getPaymentId());
        if (existingPayment == null) {
            paymentDao.insert(paymentPo);
        } else {
            paymentDao.update(paymentPo);
        }
    }

    @Override
    public Payment getPaymentById(String paymentId) {
        PaymentPo paymentPo = paymentDao.selectByPaymentId(paymentId);
        if (paymentPo == null) {
            return null;
        }
        return convertToPayment(paymentPo);
    }

    @Override
    public OrderPaymentRequest getPaymentRequestById(String orderId) {
        List<PaymentPo> paymentPos = paymentDao.selectByOrderId(orderId);
        if (paymentPos == null || paymentPos.isEmpty()) {
            return null;
        }

        OrderPaymentRequest request = new OrderPaymentRequest();
        request.setOrderId(orderId);
        request.setPayments(new ArrayList<>());

        for (PaymentPo po : paymentPos) {
            request.getPayments().add(convertToPayment(po));
        }

        return request;
    }

    private Payment convertToPayment(PaymentPo po) {
        Payment payment = new Payment();
        BeanUtils.copyProperties(po, payment);
        payment.setPaymentMethod(PaymentMethod.valueOf(po.getPaymentMethod()));
        payment.setStatus(PaymentStatus.valueOf(po.getStatus()));
        return payment;
    }
} 